package com.jml.HashMap.ExtLinkedListMap;

import java.util.LinkedList;

public class ExtLinkedListHashMap<Key,Value> {

	//map存放元素信息
	//Object[] tables = new Object[998];
	//Entry[] tables = new Entry[998];
	LinkedList<Entry>[]  tables = new LinkedList[990];


	public void put(Object key,Object value){
		Entry newEntry = new Entry(key,value);
		int hashsCode = key.hashCode();
		//两个对象作比较，如果hashcode相同对象值不一定相同
		//两个对象作比较，如果equals相同对象值一定相同，他们的hashcode也一定相同
		//hash算法是根据hashcode取模
		int hash = hashsCode % tables.length;
		System.out.println("hashsCode:"+hashsCode+"   hash:"+hash);
		//读取下标元素是否有linkedlist，如果该entryLinkedList为空就创建，这样就没有hash冲突
		LinkedList<Entry> entryLinkedList = tables[hash];
		if(entryLinkedList == null){
			entryLinkedList=new LinkedList<>();
			entryLinkedList.add(newEntry);
			tables[hash] = entryLinkedList;
		}else{
			//发生hash冲突，直接在后面添加链表节点
			for (Entry entry : entryLinkedList) {
				//解决key相同value覆盖
				if(entry.key.equals(key)){
					//equlas相同，hashcode一定相同
					entry.setValue(value);
					return;
				}else{
					//hashcode相同equals不一定相同
					entryLinkedList.add(newEntry);
				}
			}
		}
	}

	public Object get(Object key){
		int hashsCode = key.hashCode();
		int hash = hashsCode % tables.length;
		System.out.println("hashsCode:"+hashsCode+"   hash:"+hash);
		LinkedList<Entry> linkedList = tables[hash];
		for (Entry entry: linkedList) {
			if(key.equals(entry.key)){
				return entry.value;
			}
		}
		return null;
	}





}
